<template>
  <div class="calendar-view">
    <!-- 日程日期弹窗 -->
    <ScheduleDateViewDialog
      v-model:visible="dateDialogVisible"
      :selected-date="selectedDate"
      @schedule-click="handleScheduleClick"
    />
    
    <!-- 创建/修改日程弹窗 -->
    <ScheduleCreatOrModifyDialog
      v-model:visible="createDialogVisible"
      :mode="createMode"
      :default-date="selectedDateForCreate"
      @success="handleCreateSuccess"
    />
    <!-- 日历图例 -->
    <div class="calendar-legend">
      <div class="legend-group">
        <span class="legend-title">优先级：</span>
        <div class="legend-item">
          <div class="legend-color priority-urgent"></div>
          <span>紧急</span>
        </div>
        <div class="legend-item">
          <div class="legend-color priority-high"></div>
          <span>高</span>
        </div>
        <div class="legend-item">
          <div class="legend-color priority-medium"></div>
          <span>中</span>
        </div>
        <div class="legend-item">
          <div class="legend-color priority-low"></div>
          <span>低</span>
        </div>
      </div>
      <div class="legend-group">
        <span class="legend-title">状态：</span>
        <div class="legend-item">
          <el-icon class="status-icon status-pending"><Clock /></el-icon>
          <span>待处理</span>
        </div>
        <div class="legend-item">
          <el-icon class="status-icon status-in-progress"><Loading /></el-icon>
          <span>进行中</span>
        </div>
        <div class="legend-item">
          <el-icon class="status-icon status-completed"><CircleCheck /></el-icon>
          <span>已完成</span>
        </div>
        <div class="legend-item">
          <el-icon class="status-icon status-cancelled"><CircleClose /></el-icon>
          <span>已取消</span>
        </div>
      </div>
    </div>

    <el-calendar v-model="currentDate">
      <template #date-cell="{ data }">
        <div class="calendar-cell" @click="handleDateClick(data)">
          <div class="calendar-date">{{ data.day.split('-').slice(2).join('-') }}</div>
          <div class="calendar-schedules">
            <div
              v-for="schedule in getDisplaySchedulesForDate(data.day)"
              :key="schedule.id"
              class="calendar-schedule-item"
              :class="getScheduleClass(schedule)"
              @click.stop="handleScheduleClick(schedule)"
            >
              <div class="schedule-indicator" :class="getPriorityIndicatorClass(schedule.priority || 'low')"></div>
              <div class="schedule-content">
                <div class="schedule-time">{{ formatTime(schedule.start_time) }}</div>
                <div class="schedule-title">{{ schedule.title }}</div>
              </div>
            </div>
            <!-- 更多日程指示器 -->
            <div
              v-if="getMoreSchedulesCount(data.day) > 0"
              class="more-schedules-indicator"
              @click.stop="showMoreSchedule(data)"
            >
              +{{ getMoreSchedulesCount(data.day) }} 更多
            </div>
          </div>
          <!-- 待办事项计数 -->
          <div v-if="getPendingCountForDate(data.day) > 0" class="pending-count">
            {{ getPendingCountForDate(data.day) }}
          </div>
        </div>
      </template>
    </el-calendar>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useScheduleStore } from '@/stores/schedule'
import type { ScheduleResponse } from '@/api/models'
import { Clock, Loading, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import ScheduleDateViewDialog from './ScheduleDateViewDialog.vue'
import ScheduleCreatOrModifyDialog from './ScheduleCreatOrModifyDialog.vue'

interface Props {
  currentDate: Date
}

interface Emits {
  (e: 'update:currentDate', value: Date): void
  (e: 'date-click', data: any): void
  (e: 'schedule-click', schedule: ScheduleResponse): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const scheduleStore = useScheduleStore()

// 响应式状态
const dateDialogVisible = ref(false)
const selectedDate = ref('')
const createDialogVisible = ref(false)
const createMode = ref<'create' | 'edit'>('create')
const selectedDateForCreate = ref<string>('')

// 计算属性
const currentDate = computed({
  get: () => props.currentDate,
  set: (value) => emit('update:currentDate', value)
})

// 方法
const getSchedulesForDate = (dateString: string) => {
  return scheduleStore.schedules.filter(schedule => {
    const scheduleDate = new Date(schedule.start_time).toISOString().split('T')[0]
    return scheduleDate === dateString
  })
}

// 获取排序后的日程（已完成日程放到最后）
const getSortedSchedulesForDate = (dateString: string) => {
  const schedules = getSchedulesForDate(dateString)
  return schedules.sort((a, b) => {
    // 已完成的日程放到最后
    if (a.status === 'completed' && b.status !== 'completed') return 1
    if (a.status !== 'completed' && b.status === 'completed') return -1
    
    // 已取消的日程也放到最后
    if (a.status === 'cancelled' && b.status !== 'cancelled') return 1
    if (a.status !== 'cancelled' && b.status === 'cancelled') return -1
    
    // 其他状态按开始时间排序
    return new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
  })
}

// 获取显示的日程（最多显示两个）
const getDisplaySchedulesForDate = (dateString: string) => {
  const sortedSchedules = getSortedSchedulesForDate(dateString)
  return sortedSchedules.slice(0, 1)
}

// 获取更多日程的数量
const getMoreSchedulesCount = (dateString: string) => {
  const totalSchedules = getSchedulesForDate(dateString).length
  const displaySchedules = getDisplaySchedulesForDate(dateString).length
  return totalSchedules - displaySchedules
}

const getScheduleClass = (schedule: ScheduleResponse) => {
  return {
    [`priority-${schedule.priority}`]: true,
    [`status-${schedule.status}`]: true
  }
}

const getPriorityIndicatorClass = (priority: string) => {
  return `priority-indicator-${priority}`
}


const getPendingCountForDate = (dateString: string) => {
  return scheduleStore.schedules.filter(schedule => {
    const scheduleDate = new Date(schedule.start_time).toISOString().split('T')[0]
    return scheduleDate === dateString && schedule.status === 'pending'
  }).length
}

const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handleDateClick = (data: any) => {
  emit('date-click', data)
  
  // 检查是否按住了修饰键（如 Alt 或 Option）
  if (data.event && (data.event.altKey || data.event.metaKey)) {
    // 如果按住了修饰键，显示该日期的所有日程
    selectedDate.value = data.day
    dateDialogVisible.value = true
  } else {
    // 否则，打开创建日程对话框，传入点击的日期
    selectedDateForCreate.value = data.day
    createMode.value = 'create'
    createDialogVisible.value = true
  }
}

const showMoreSchedule = (data: any) => {
  selectedDate.value = data.day
  dateDialogVisible.value = true
}

const handleScheduleClick = (schedule: ScheduleResponse) => {
  emit('schedule-click', schedule)
}

const handleCreateSuccess = () => {
  // 日程创建成功后的处理
  // 可以在这里刷新日程列表或执行其他操作
}
</script>

<style scoped>
.calendar-view {
  background: var(--card-bg);
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px var(--shadow-color);
  overflow: hidden;
}


/* 日历图例 */
.calendar-legend {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
  border-bottom: 1px solid var(--el-border-color-light);
  flex-wrap: wrap;
  gap: 16px;
}

.legend-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.legend-title {
  font-size: 12px;
  font-weight: 600;
  color: var(--el-text-color-secondary);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  color: var(--el-text-color-regular);
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

/* 状态颜色 */
.legend-color.status-pending {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.legend-color.status-in-progress {
  background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%);
}

.legend-color.status-completed {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.legend-color.status-cancelled {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
}

/* 优先级颜色 */
.legend-color.priority-urgent {
  background: linear-gradient(135deg, #DC143C 0%, #FF1744 100%);
}

.legend-color.priority-high {
  background: linear-gradient(135deg, #F56C6C 0%, #FF6B6B 100%);
}

.legend-color.priority-medium {
  background: linear-gradient(135deg, #E6A23C 0%, #FFB84D 100%);
}

.legend-color.priority-low {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
}

.calendar-cell {
  height: 100%;
  padding: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.calendar-cell:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

.calendar-date {
  font-size: 12px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  text-align: center;
}

.calendar-schedules {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.calendar-schedule-item {
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  position: relative;
  display: flex;
  align-items: center;
  gap: 4px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.calendar-schedule-item:hover {
  transform: translateY(-1px) scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.schedule-indicator {
  width: 4px;
  height: 12px;
  border-radius: 2px;
  flex-shrink: 0;
}

.schedule-content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 2px;
  min-width: 0;
}

.schedule-time {
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  flex-shrink: 0;
}

.schedule-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: rgba(255, 255, 255, 0.95);
  font-weight: 500;
}

/* 待办事项计数 */
.pending-count {
  position: absolute;
  top: 4px;
  right: 4px;
  background: linear-gradient(135deg, #F56C6C 0%, #FF6B6B 100%);
  color: white;
  font-size: 10px;
  font-weight: 600;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(245, 108, 108, 0.3);
  z-index: 5;
}

/* 更多日程指示器 */
.more-schedules-indicator {
  font-size: 9px;
  font-weight: 600;
  color: var(--el-color-primary);
  background: rgba(var(--el-color-primary-rgb), 0.1);
  border: 1px solid rgba(var(--el-color-primary-rgb), 0.2);
  border-radius: 4px;
  padding: 1px 4px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  backdrop-filter: blur(5px);
}

.more-schedules-indicator:hover {
  background: rgba(var(--el-color-primary-rgb), 0.15);
  border-color: var(--el-color-primary);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.2);
}

/* 优先级样式 */
.calendar-schedule-item.priority-urgent {
  background: linear-gradient(135deg, rgba(220, 20, 60, 0.95) 0%, rgba(255, 23, 68, 0.9) 100%);
  border-color: rgba(220, 20, 60, 0.4);
  animation: pulse-urgent 2s infinite;
}

.calendar-schedule-item.priority-high {
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.9) 0%, rgba(255, 107, 107, 0.8) 100%);
  border-color: rgba(245, 108, 108, 0.3);
}

.calendar-schedule-item.priority-medium {
  background: linear-gradient(135deg, rgba(230, 162, 60, 0.9) 0%, rgba(255, 184, 77, 0.8) 100%);
  border-color: rgba(230, 162, 60, 0.3);
}

.calendar-schedule-item.priority-low {
  background: linear-gradient(135deg, rgba(144, 147, 153, 0.9) 0%, rgba(177, 179, 184, 0.8) 100%);
  border-color: rgba(144, 147, 153, 0.3);
}

/* 状态样式 */
.calendar-schedule-item.status-pending {
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
}

.calendar-schedule-item.status-in-progress {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.calendar-schedule-item.status-completed {
  opacity: 0.7;
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.7) 0%, rgba(133, 206, 97, 0.6) 100%) !important;
  text-decoration: line-through;
}

.calendar-schedule-item.status-cancelled {
  opacity: 0.5;
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.5) 0%, rgba(247, 137, 137, 0.4) 100%) !important;
  text-decoration: line-through;
}

/* 优先级指示器 */
.priority-indicator-urgent {
  background: linear-gradient(135deg, #FF1744 0%, #FF5252 100%);
  box-shadow: 0 1px 3px rgba(255, 23, 68, 0.6);
  animation: pulse-indicator 1.5s infinite;
}

.priority-indicator-high {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
  box-shadow: 0 1px 3px rgba(255, 107, 107, 0.5);
}

.priority-indicator-medium {
  background: linear-gradient(135deg, #FFB84D 0%, #FFCC7A 100%);
  box-shadow: 0 1px 3px rgba(255, 184, 77, 0.5);
}

.priority-indicator-low {
  background: linear-gradient(135deg, #B1B3B8 0%, #D3D5D8 100%);
  box-shadow: 0 1px 3px rgba(177, 179, 184, 0.5);
}

/* Element Plus 日历组件样式覆盖 */
:deep(.el-calendar) {
  border-radius: var(--border-radius);
}

:deep(.el-calendar__header) {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-light);
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
}

:deep(.el-calendar__body) {
  padding: 8px;
}

:deep(.el-calendar-table) {
  width: 100%;
}

:deep(.el-calendar-table td) {
  border: 1px solid var(--el-border-color-lighter);
  vertical-align: top;
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 80px;
  padding: 4px;
  transition: all 0.2s ease;
}

:deep(.el-calendar-table .el-calendar-day:hover) {
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

:deep(.el-calendar-table .current) {
  background-color: rgba(var(--el-color-primary-rgb), 0.02);
}

:deep(.el-calendar-table .today) {
  background-color: rgba(var(--el-color-primary-rgb), 0.08);
}

:deep(.el-calendar-table .today .calendar-date) {
  color: var(--el-color-primary);
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .calendar-view {
    margin: 0 -8px;
    border-radius: 0;
  }
  
  .calendar-legend {
    padding: 12px;
    gap: 12px;
  }
  
  .legend-group {
    gap: 8px;
  }
  
  .legend-title {
    font-size: 11px;
  }
  
  .legend-item {
    font-size: 10px;
    gap: 4px;
  }
  
  .legend-color {
    width: 10px;
    height: 10px;
  }
  
  :deep(.el-calendar-table .el-calendar-day) {
    height: 60px;
    padding: 2px;
  }
  
  .calendar-date {
    font-size: 11px;
    margin-bottom: 2px;
  }
  
  .calendar-schedule-item {
    font-size: 9px;
    padding: 1px 2px;
    gap: 2px;
  }
  
  .schedule-time {
    display: none;
  }
  
  .schedule-indicator {
    width: 3px;
    height: 8px;
  }
  
  .pending-count {
    width: 14px;
    height: 14px;
    font-size: 9px;
  }
}

/* 状态图标样式 */
.status-icon {
  font-size: 12px;
  font-weight: 600;
}

.status-icon-pending {
  color: #E6A23C;
}

.status-icon-in-progress {
  color: #409EFF;
  animation: spin 2s linear infinite;
}

.status-icon-completed {
  color: #67C23A;
}

.status-icon-cancelled {
  color: #F56C6C;
}

/* 状态指示器容器 */
.schedule-status-indicator {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 2px;
}

/* 动画效果 */
@keyframes pulse-urgent {
  0%, 100% {
    box-shadow: 0 2px 8px rgba(220, 20, 60, 0.4);
  }
  50% {
    box-shadow: 0 2px 16px rgba(220, 20, 60, 0.8);
  }
}

@keyframes pulse-indicator {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@media (max-width: 480px) {
  :deep(.el-calendar-table .el-calendar-day) {
    height: 50px;
    padding: 1px;
  }
  
  .calendar-date {
    font-size: 10px;
    margin-bottom: 1px;
  }
  
  .calendar-schedule-item {
    font-size: 8px;
    padding: 1px;
    line-height: 1.1;
    gap: 1px;
  }
  
  .schedule-title {
    max-width: 100%;
  }
  
  .schedule-indicator {
    width: 2px;
    height: 6px;
  }
  
  .schedule-status-indicator {
    margin-left: 1px;
  }
  
  .status-icon {
    font-size: 10px;
  }
  
  .pending-count {
    width: 12px;
    height: 12px;
    font-size: 8px;
  }
}
</style>
